package d.max.rwp.ui.component;

import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import d.max.rwp.R;
import java.io.File;
import java.util.Random;
import java.util.logging.Handler;

/**
 * author: Maxim Dybarskiy
 * date:   Sep 4, 2011
 * time:   10:22:04 PM
 */
public class FilelistView extends ListView {
    
    private FileListAdapter adapter = new FileListAdapter();
    
    public FilelistView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    public FilelistView(Context context) {
        super(context);
        init();
    }
    
    private void init() {
        this.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        // init UI interaction
        this.setAdapter(adapter);
        this.setOnItemClickListener(new OnClickListener());
        this.setOnItemLongClickListener(new OnShowPreviewListener());
        // show root folder
        adapter.showContent(new File("/"));
    }
    
    private void setCheckedState(File file, CheckedTextView view) {
        // test version. need to provide real synchronization
        view.setChecked(new Random().nextBoolean());
    }
    
    private void addToList(File file) {
        
    }
    
    private void removeFromList(File file) {
        
    }
    
    private Drawable getCheckMark() {
            Drawable mark;
            int[] attrs = { android.R.attr.listChoiceIndicatorMultiple };
            TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs);
            mark = ta.getDrawable(0);
            ta.recycle();
            return mark;
        }
    
    private class OnClickListener implements OnItemClickListener {
        
        @Override
        public void onItemClick(AdapterView<?> av, View view, int i, long l) {
            File file = adapter.content[i];
            // navigate to folder if click on it
            if (file.isDirectory()) {
                adapter.showContent(file);
            } else {
                // add file to random list
                // TODO: delete this debug toast and add file to list
                Toast.makeText(FilelistView.this.getContext(),
                        "file stored",
                        Toast.LENGTH_SHORT).show();
            }
            view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
        }
    }
    
    private class OnShowPreviewListener implements AdapterView.OnItemLongClickListener {
        
        @Override
        public boolean onItemLongClick(AdapterView<?> av, View view, int i, long l) {
            if (!adapter.content[i].isDirectory()) {
                new ImagePreviewDialog(FilelistView.this.getContext(),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface di, int i) {
                                // TODO: delete this debug toast and add file to list
                                Toast.makeText(FilelistView.this.getContext(),
                                        "file stored",
                                        Toast.LENGTH_SHORT).show();
                            }
                        },
                        adapter.content[i]).show();
                return true;
            } else {
                return false;
            }
        }
    }
    
    private class FileListAdapter extends BaseAdapter {
        
        private File[] content = new File[0];
        
        @Override
        public int getCount() {
            return content.length;
        }
        
        @Override
        public Object getItem(int i) {
            return content[i];
        }
        
        @Override
        public long getItemId(int i) {
            return content[i].hashCode();
        }
        
        @Override
        public boolean isEnabled(int position) {
            return content[position].canRead();
        }
        
        @Override
        public View getView(int i, View view, ViewGroup vg) {
            File file = content[i];
            TextView res = null;
            // init view
            if (file.isDirectory()) {
                res = new TextView(FilelistView.this.getContext());
            } else {
                res = new CheckedTextView(FilelistView.this.getContext());
                CheckedTextView checkedView =  (CheckedTextView) res;
                // synchronize state of file with list of choosen files
                setCheckedState(file, checkedView);
                // add checkbox icon
                checkedView.setCheckMarkDrawable(getCheckMark());
            }
            // set attributes
            res.setGravity(Gravity.CENTER_VERTICAL);
            res.setPadding(15, 10, 0, 15);
            res.setTextSize(TypedValue.COMPLEX_UNIT_PT, 10);
            res.setText(file.getName());
            // change font style for directory
            if (file.isDirectory()) {
                res.setTypeface(Typeface.DEFAULT_BOLD);
            }
            // if can`t read set dark color
            // TODO: need to provide style (now color is the same for selected and simple item)
            if (!file.canRead()) {
                res.setTextColor(getResources().getColor(R.color.unreadable));
                res.setEnabled(false);
            } else {
                res.setTextColor(getResources().getColor(R.color.readable));
                res.setHapticFeedbackEnabled(true);
            }
            return res;
        }
        
        void showContent(File folder) {
            if (folder.exists()
                    && folder.isDirectory()
                    && folder.canRead()) {
                // load content of the folder
                File[] files = folder.listFiles();
                content = new File[files.length + 1];
                // add parent folder
                content[0] = new File(folder + "/..");
                System.arraycopy(files, 0, content, 1, files.length);
                // update listview
                notifyDataSetChanged();
                // scroll to first item
                FilelistView.this.setSelection(0);
            }
        }
    }
}
